package com.tianji.promotion.utils;

import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.core.Ordered;

//通知
@Aspect
@RequiredArgsConstructor
public class MyLockAspect implements Ordered {

    private final RedissonClient redissonClient;

    @Around("@annotation(myLock)")
    public Object tryLock(ProceedingJoinPoint pjp,MyLock myLock) throws Throwable {
        //1.创建锁对象
        RLock lock = redissonClient.getLock(myLock.name());
        //2.尝试获取锁
        boolean islock = lock.tryLock(myLock.waitTime(), myLock.leaseTime(), myLock.unit());
        //3.判断是否成功
        if (!islock){
            //3.1失败，抛异常
            throw  new BootstrapMethodError("请求太频繁!");
        }
        try {
            //3.2成功，执行业务
            return pjp.proceed();
        }finally {
            //释放锁
            lock.unlock();
        }

    }

    @Override
    public int getOrder() {
        return 0;
    }
}
